import React, {FC, useCallback, useEffect, useMemo, useState} from "react";
import "./css/SelectIcon.less";
import GlobalIcon from "../../global/GlobalIcon.tsx";
import {Button} from "antd";
import {useTranslation} from "react-i18next";
import {coreDispatch} from "../../utils/StoreUtil.tsx";
import SelectIconModal from "../../component/modal/select/SelectIconModal.tsx";

interface SelectIconProps {
    onChange?: Function,
    value?: string,
    ds?: any,
    iconType?: string,
    disabled: boolean
}

const SelectIcon: FC<SelectIconProps> = (props) => {
    const {t} = useTranslation();

    const [isClose, setIsClose] = useState<boolean>(false),
        [icon, setIcon] = useState<string>("");

    useEffect(() => {
        const {ds = {}}: { ds?: any } = props;
        let newValue = ds.value || props.value;
        setIcon(newValue);
        newValue && setIsClose(true);
    }, [props.ds]);

    const handleChange = useCallback((value: string) => {
        setIcon(value);
        value ? setIsClose(true) : setIsClose(false);
        props.onChange && props.onChange(value || "");
    }, [props.onChange]);

    const handleShowIcon = useCallback(() => {
        coreDispatch("modalReducer/createModal", {
            key: "selectIcon" + Math.random(),
            modalProps: {
                title: t("selectIcon"),
                width: 800,
            },
            component: SelectIconModal,
            comProps: {
                value: icon
            },
            onFinish: (result: any) => {
                if (result.data) {
                    handleChange(result.data);
                }
            }
        })
    }, [icon]);

    const renderSelectIcon = useMemo(() => {
        const {disabled}: { disabled: boolean } = props;
        return (
            <div className={"sf_core_icon_list " + (disabled ? "select_icon_disabled" : "")}>
                <div className="sf_core_icon_list_box">
                    <GlobalIcon size={50} name={icon || "icon-un-picture"}/>
                    {isClose ? <div className="sf_core_icon_list_box_delete">
                        <GlobalIcon onClick={() => {
                            handleChange("")
                        }} size={16} name={"icon-delete"}/>
                    </div> : null}
                </div>
                {!disabled ?
                    <div className="sf_core_icon_list_btn">
                        <Button onClick={handleShowIcon} style={{marginBottom: 5}} type={"primary"}
                                danger>{t("selectIcon")}</Button>
                    </div> : null}
            </div>
        )
    }, [icon, isClose, props.disabled]);

    return (renderSelectIcon);
};

export default SelectIcon;